package com.cl.it.spider;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.concurrent.TimeUnit;

public class SeleniumSpider {

    protected String chomeDriver;
    protected String proxyStr;
    protected Long pageTimeout;
    protected Long domTimeout;

    protected WebDriver driver;

    protected WebDriverWait wait;

    public SeleniumSpider() {

    }

    public SeleniumSpider(String chomeDriver) {
        this.chomeDriver = chomeDriver;
        init();
    }

    public SeleniumSpider(String chomeDriver, String proxyStr) {
        this.chomeDriver = chomeDriver;
        this.proxyStr = proxyStr;
        init();
    }

    public SeleniumSpider(String chomeDriver, String proxyStr, Long pageTimeout, Long domTimeout) {
        this.chomeDriver = chomeDriver;
        this.proxyStr = proxyStr;
        this.pageTimeout = pageTimeout;
        this.domTimeout = domTimeout;
        init();
    }

    public void init() {
        System.setProperty("webdriver.chrome.driver", chomeDriver);
        ChromeOptions options = new ChromeOptions();

        //设置代理
        if (StringUtils.isNotBlank(proxyStr)) {
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(proxyStr);
            options.setProxy(proxy);
        }
        WebDriver driver = new ChromeDriver(options);
        long pt = pageTimeout == null ? 60 * 1000L : pageTimeout;
        long dt = domTimeout == null ? 3 * 1000 : domTimeout;
        driver.manage().timeouts().pageLoadTimeout(pt, TimeUnit.MILLISECONDS);
        driver.manage().timeouts().implicitlyWait(dt, TimeUnit.MILLISECONDS);

        WebDriverWait wait = new WebDriverWait(driver, dt);

        this.driver = driver;
        this.wait = wait;
    }

    public WebDriver getDriver() {
        return driver;
    }

    public WebDriverWait getWait() {
        return wait;
    }
}
